import { Model, DataTypes } from 'sequelize';
import sequelize from '../config/database.js';
import bcrypt from 'bcryptjs';
import QRCode from 'qrcode';

export default class User extends Model {
  // 生成用户二维码
  async generateQRCode() {
    const qrData = {
      userId: this.id,
      type: 'user-profile'
    };
    return await QRCode.toDataURL(JSON.stringify(qrData));
  }

  // 验证密码
  async validatePassword(password) {
    if (!password || !this.password) {
      console.log('Missing password or stored password');
      return false;
    }
    try {
      console.log('Comparing passwords:', { input: password, stored: this.password });
      const result = await bcrypt.compare(password, this.password);
      console.log('Password comparison result:', result);
      return result;
    } catch (error) {
      console.error('Password validation error:', error);
      return false;
    }
  }

  static initModel(sequelize) {
    User.init({
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      email: {
        type: DataTypes.STRING(100),
        allowNull: false,
        unique: true,
        validate: {
          isEmail: {
            msg: '请输入有效的邮箱地址'
          },
          notNull: {
            msg: '邮箱不能为空'
          }
        },
        comment: '邮箱'
      },
      phone: {
        type: DataTypes.STRING(20),
        allowNull: true,
        unique: true,
        validate: {
          is: {
            args: /^1[3-9]\d{9}$/,
            msg: '请输入有效的手机号码'
          }
        }
      },
      password: {
        type: DataTypes.STRING(255),
        allowNull: true,
        validate: {
          len: {
            args: [6, 20],
            msg: '如果设置密码，长度必须在6-20位之间'
          }
        }
      },
      nickname: {
        type: DataTypes.STRING(50),
        allowNull: false,
        validate: {
          notNull: {
            msg: '昵称不能为空'
          },
          len: {
            args: [2, 20],
            msg: '昵称长度必须在2-20位之间'
          }
        },
        comment: '昵称'
      },
      avatar: {
        type: DataTypes.STRING(255),
        defaultValue: () => {
          const baseUrl = process.env.SERVER_URL || '';
          // 移除末尾的斜杠（如果有）
          const cleanBaseUrl = baseUrl.replace(/\/+$/, '');
          return cleanBaseUrl + '/uploads/default-avatars/cartoon-1.png';
        },
        comment: '头像'
      },
      qrCode: {
        type: DataTypes.TEXT,
        allowNull: true
      },
      status: {
        type: DataTypes.ENUM('online', 'offline'),
        defaultValue: 'offline'
      },
      lastLoginAt: {
        type: DataTypes.DATE
      }
    }, {
      sequelize,
      modelName: 'User',
      tableName: 'users',
      timestamps: true,
      hooks: {
        beforeCreate: async (user) => {
          if (user.changed('password')) {
            const salt = await bcrypt.genSalt(10);
            user.password = await bcrypt.hash(user.password, salt);
          }
          // 生成二维码
          user.qrCode = await user.generateQRCode();
        },
        beforeUpdate: async (user) => {
          if (user.changed('password')) {
            const salt = await bcrypt.genSalt(10);
            user.password = await bcrypt.hash(user.password, salt);
          }
        }
      }
    });
    return User;
  }
}

User.initModel(sequelize);
